package com.hcss.login.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hcss.common.base.BaseClass;
import com.hcss.common.constant.ConfigConstants;
import com.hcss.common.constant.WechatApiConstants;
import com.hcss.common.redis.base.RedisMapDao;
import com.hcss.common.util.BeanCopyUtil;
import com.hcss.common.util.EmptyUtil;
import com.hcss.common.util.HttpClientUtil;
import com.hcss.common.vo.ResultMsg;
import com.hcss.common.vo.Results;
import com.hcss.login.constant.LoginConstants;
import com.hcss.login.service.LoginService;
import com.hcss.qywechat.app.dao.WQyAppMapper;
import com.hcss.qywechat.app.model.WQyApp;
import com.hcss.qywechat.app.model.WQyAppExample;
import com.hcss.qywechat.user.dao.WQyUserMapper;
import com.hcss.qywechat.user.model.WQyUser;
import com.hcss.qywechat.user.model.WQyUserExample;
import com.hcss.qywechat.user.model.vo.WQyUserVO;
import com.hcss.sys.role.dao.HcSysRoleComplexMapper;
import com.hcss.sys.user.dao.HcSysUseragentMapper;
import com.hcss.sys.user.dao.HcSysUserbelongapMapper;
import com.hcss.sys.user.model.HcSysUseragent;
import com.hcss.sys.user.model.HcSysUseragentExample;
import com.hcss.sys.user.model.HcSysUserbelongap;
import com.hcss.sys.user.model.HcSysUserbelongapExample;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @描述: 登录功能提供服务接口实现类
 * @作者: xuqian
 * @创建日期: 2018-06-27 9:30
 * @公司 浙江鸿程计算机系统有限公司
 */
@Slf4j
@Service("loginService")
public class LoginServiceImpl extends BaseClass implements LoginService {

    @Autowired
    private RedisMapDao<String, Object> redisMapDao;

    @Autowired
    private WQyAppMapper wQyAppMapper;

    @Autowired
    private ConfigConstants configConstants;

    @Autowired
    private WQyUserMapper wQyUserMapper;

    @Autowired
    private HcSysRoleComplexMapper hcSysRoleComplexMapper;

    @Autowired
    private HcSysUserbelongapMapper hcSysUserbelongapMapper;

    @Autowired
    private HcSysUseragentMapper hcSysUseragentMapper;

    @Override
    public boolean checkAgentid(Long agentid) {
        WQyApp app = getAppByAgentid(agentid);
        return app != null;
    }

    @Override
    public ResultMsg getUserByCode(String code, Long agentid) {
        WQyApp app = getAppByAgentid(agentid);
        String accesstoken = "lasjldfjha9u0u0oijdfaiuh";
        if (StringUtils.isBlank(accesstoken)) {
            return new ResultMsg(Results.ERROR, "请确定应用配置正确性");
        }

        String url = WechatApiConstants.OAUTH2_GETUSERINFO.replace(WechatApiConstants.Placeholder.ACCESS_TOKEN, accesstoken)
                .replace(WechatApiConstants.Placeholder.CODE, code);
        JSONObject result = HttpClientUtil.doGetJSON(url);
        int errorcode = result.getIntValue(WechatApiConstants.Result.ERRCODE);
        if (errorcode != WechatApiConstants.Result.CODE_SECCESS) {
            log.error("无法获取访问用户信息， 请求结果：{}", result.toJSONString());
            return new ResultMsg(Results.ERROR, "授权失败，请重新操作");
        }

        String userid = result.getString(WechatApiConstants.Result.USERID);
        if (StringUtils.isBlank(userid)) {
            return new ResultMsg(Results.ERROR, "非法用户访问");
        }

        WQyUserVO user = getUserByUserid(userid);
        if (user == null) {
            return new ResultMsg(Results.ERROR, "用户信息未录入，请联系管理员录入");
        }
        return new ResultMsg(user);
    }

    @Override
    public void clearLoginCache(String userid) {
        redisMapDao.clear(LoginConstants.getRedisCacheLoginUserMenuKey(userid));
    }

    private WQyApp getAppByAgentid(Long agentid) {
        WQyAppExample example = new WQyAppExample();
        example.createCriteria().andCorpidEqualTo(configConstants.getWechat().getCorpid())
                .andAppidEqualTo(agentid).andSecretIsNotNull();
        List<WQyApp> list = wQyAppMapper.selectByExample(example);
        return CollectionUtils.isNotEmpty(list) ? list.get(0) : null;
    }

    @Override
    public WQyUserVO getUserByUserid(String userid) {
        WQyUserExample wQyUserExample = new WQyUserExample();
        wQyUserExample.createCriteria().andCorpidEqualTo(configConstants.getWechat().getCorpid())
                .andUseridEqualTo(userid);
        List<WQyUser> list = wQyUserMapper.selectByExample(wQyUserExample);
        WQyUserVO user = null;
        try {
            user = BeanCopyUtil.copyConvey(list.get(0), WQyUserVO.class);
        } catch (Exception e) {
        }
        if (user == null) {
            return null;
        }

        List<String> roleList = hcSysRoleComplexMapper.selectUserRoleCode(userid);
        user.setRoles(roleList);

        // TODO 查询所属机场 可能存在多个，暂时这么做，以后再改造
        HcSysUserbelongapExample belongapExample = new HcSysUserbelongapExample();
        belongapExample.createCriteria().andUseridEqualTo(user.getUserid());
        List<HcSysUserbelongap> userbelongaps = hcSysUserbelongapMapper.selectByExample(belongapExample);
        if (!EmptyUtil.isEmpty(userbelongaps)) {
            user.setBelongap(userbelongaps.get(0).getBelongap());
        }

        // 查询所属货代
        HcSysUseragentExample useragentExample = new HcSysUseragentExample();
        useragentExample.createCriteria().andUseridEqualTo(user.getUserid());
        List<HcSysUseragent> useragents = hcSysUseragentMapper.selectByExample(useragentExample);
        if (!EmptyUtil.isEmpty(useragents)) {
            List<String> agents = new ArrayList<>();
            for (HcSysUseragent agent : useragents) {
                agents.add(agent.getAgentcode());
            }
            user.setAgents(agents);
        }
        return user;
    }
}
